import qs from "qs" // querystring 
export const ajax = {
  get(url,params){
    var pro = new Promise(function(resolve,reject){
       
       var client = new XMLHttpRequest();
       params = params ? qs.stringify(params):params;  // 转成字符串 
       console.log(params);
       client.open("GET",url+"?"+params,true);
       client.send()
       client.onreadystatechange = function(){  // 监听数据返回
          // status = 200
          // readyState = 4 
          if(client.readyState!=4){  // 0 1 2 3  
            return ''
          }
          if(client.status==200){
            resolve({
              data:JSON.parse(client.responseText)
            })
          }else{
            reject(new Error(client.statusText))
          }
       }
    })
    return pro;
  },
  post(url,body){
    var pro = new Promise(function(resolve,reject){
       
      var client = new XMLHttpRequest();
      body = body?qs.stringify(body):body; 
      client.open("POST",url,true);
      // 设置 请求头
      client.setRequestHeader("content-type","application/x-www-form-urlencoded")
      client.send(body)
      client.onreadystatechange = function(){  // 监听数据返回
         // status = 200
         // readyState = 4 
         if(client.readyState!=4){  // 0 1 2 3  
           return ''
         }
         if(client.status==200){
           resolve({
             data:JSON.parse(client.responseText)
           })
         }else{
           reject(new Error(client.statusText))
         }
      }

   })
   return pro;
  }
}